package com.taptech.doufu.db.history;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.services.history.ReadRecord;
import com.taptech.doufu.util.TextUtil;

public class Read_DataBaseUtil
{
    private DatabaseHelper helper;
    public static final String lock = "access";
    private final String TABLE_NAME = DatabaseHelper.TABLE_NAME;
    private final String DB_NAME = DatabaseHelper.DBNAME;

    public Read_DataBaseUtil(Context context)
    {
        helper = new DatabaseHelper(context, DB_NAME, null, Constant.DB_VERSION);
    }

    // 添加记录
    public void insert(String novelid, String sectionid, int position, int allnum, String name, String time,String imgUrl,int type)
    {
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL("INSERT INTO " + TABLE_NAME + " (novelid,sectionid,position,allnum,name,time,imgurl,type) VALUES (?,?,?,?,?,?,?,?)", new Object[]{novelid, sectionid, position, allnum, name, time, imgUrl,type});
        print("AnalysisDataBaseUtil------成功添加");
        db.close();
    }

    /**
     *
     * 对话小说添加记录
     * @param novelid
     * @param name
     */
    public void insert(String novelid,String name,String progress)
    {
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL("INSERT INTO " + TABLE_NAME + " (novelid,name,time,progress,type) VALUES (?,?,?,?,?)", new Object[]{novelid, name,getTimeBySystem(), progress, Constant.OBJECT_TYPE_CHATNOVEL});
        print("AnalysisDataBaseUtil------成功添加");
        db.close();
    }


    /**
     * 批量插入数据
     * @param list
     */
    public void insertList(List<ReadRecord> list) {
        SQLiteDatabase db = helper.getWritableDatabase();
        try {
            db.beginTransaction();
            for (int i = 0; i < list.size(); i++) {
                ReadRecord model = list.get(i);
                if (model == null) {
                    continue;
                }
                db.execSQL("INSERT INTO " + TABLE_NAME + " (novelid,sectionid,position,allnum,name,time,imgurl,type,progress) VALUES (?,?,?,?,?,?,?,?,?)",
                        new Object[]{model.getNovel_id(), model.getSection_id(), model.getPosition(), model.getAll_num(), model.getName(), model.getTime(), model.getImg_url(),model.getType()});
            }
            db.setTransactionSuccessful();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            db.endTransaction();
            db.close();
        }
    }

    /**
     * 判断数据表是否为空
     * @return
     */
    public boolean isDBTableNull() {
        if(helper!=null){
            SQLiteDatabase db = helper.getWritableDatabase();
            Cursor c = db.rawQuery("SELECT novelid FROM " + TABLE_NAME, null);
            while (c.moveToNext()) {
                return false;
            }
            c.close();
            db.close();
            return true;
        }else{
            return true;
        }
    }



    // 删除记录
    public void delete(String novelid)
    {
        if (novelid == null)
        {
            return;
        }
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL("DELETE FROM " + TABLE_NAME + " WHERE novelid = ? ", new Object[]{novelid});
        print("AnalysisDataBaseUtil------成功删除");
        db.close();
    }

    /**
     * 更新对话小说阅读记录
     * @param novelid
     * @param name
     */
    public void update(String novelid, String name,String progress)
    {
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL("UPDATE " + TABLE_NAME + " SET progress = ?  WHERE novelid = ? ", new Object[]{progress, novelid});
        db.execSQL("UPDATE " + TABLE_NAME + " SET name = ? WHERE novelid = ? ", new Object[]{name, novelid});
        db.execSQL("UPDATE " + TABLE_NAME + " SET time = ? WHERE novelid = ? ", new Object[]{getTimeBySystem(), novelid});
        db.execSQL("UPDATE " + TABLE_NAME + " SET type = ? WHERE novelid = ? ", new Object[]{Constant.OBJECT_TYPE_CHATNOVEL, novelid});
        print("AnalysisDataBaseUtil------成功更新");
        db.close();
    }


    /**
     * 修改某个作品的状态
     * @param novelid
     * @param needSync
     */
    public void update(String novelid, int needSync) {
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL("UPDATE " + TABLE_NAME + " SET needSync = ? WHERE novelid = ? ", new Object[]{needSync, novelid});
        print("AnalysisDataBaseUtil------成功更新");
        db.close();
    }

    /**
     * 修改所有数据的状态
     * @param needSync
     */
    public void update(int needSync) {
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL("UPDATE " + TABLE_NAME + " SET needSync = ? ", new Object[]{needSync});
        db.close();
    }

    private static String getTimeBySystem() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = dateFormat.format(new Date());// 可以将时间保存起来
        return dateStr;
    }


    public static void updateChatNovelRecord(Context context,String id,String title,String progress) {
        Read_DataBaseUtil mRead_DataBaseUtil;
        ReadRecord readRecord;
        try {
            mRead_DataBaseUtil = new Read_DataBaseUtil(context);
            readRecord = mRead_DataBaseUtil.queryHistoryInfo(String.valueOf(id));
            if (readRecord != null) {
                mRead_DataBaseUtil.update(id,title,progress);
            }else {
                mRead_DataBaseUtil.insert(id,title,progress);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 更新记录
    public void update(String novelid, String sectionid, int position, int allnum, String name, String time,String imgUrl,int type) {
        SQLiteDatabase db = helper.getWritableDatabase();
        db.execSQL("UPDATE " + TABLE_NAME + " SET sectionid = ?  WHERE novelid = ? ", new Object[]{sectionid, novelid});
        db.execSQL("UPDATE " + TABLE_NAME + " SET position = ? WHERE novelid = ? ", new Object[]{position, novelid});
        db.execSQL("UPDATE " + TABLE_NAME + " SET allnum = ? WHERE novelid = ? ", new Object[]{allnum, novelid});
        db.execSQL("UPDATE " + TABLE_NAME + " SET name = ? WHERE novelid = ? ", new Object[]{name, novelid});
        db.execSQL("UPDATE " + TABLE_NAME + " SET time = ? WHERE novelid = ? ", new Object[]{time, novelid});
        db.execSQL("UPDATE " + TABLE_NAME + " SET imgurl = ? WHERE novelid = ? ", new Object[]{imgUrl, novelid});
        db.execSQL("UPDATE " + TABLE_NAME + " SET type = ? WHERE novelid = ? ", new Object[]{type, novelid});
        print("AnalysisDataBaseUtil------成功更新");
        db.close();
    }

    // 查询novelId
    public List<String> queryNovelId()
    {
        if(helper!=null){
            SQLiteDatabase db = helper.getWritableDatabase();
            Cursor c = db.rawQuery("SELECT novelid FROM " + TABLE_NAME, null);//根据id倒序显示:+" ORDER BY _id DESC"
            List<String> novelIdList = new ArrayList<String>();
            while (c.moveToNext())
            {
                if (c.getString(0) != null && !c.getString(0).equalsIgnoreCase("null"))
                {
                    novelIdList.add(c.getString(0));
                }
            }
            c.close();
            db.close();
            return novelIdList;
        }else{
            return null;
        }
    }


    // 查询阅读记录
    public ReadRecord queryHistoryInfo(String novelid) {
        if (TextUtils.isEmpty(novelid)) {
            return null;
        }
        if (helper == null) {
            return null;
        }
        try {
            SQLiteDatabase db = helper.getWritableDatabase();
            Cursor c = db.rawQuery("SELECT sectionid,position,allnum,name,time,imgurl,progress,type FROM " + TABLE_NAME + " WHERE novelid = ? ", new String[]{novelid});
            ReadRecord record = null;
            if (c.moveToNext()) {
                record = new ReadRecord(c.getString(0), c.getInt(1), c.getInt(2), c.getString(3),
                        c.getString(4), novelid,c.getString(5),c.getString(6),c.getInt(7));
            }
            c.close();
            db.close();
            return record;
        } catch (Exception e) {
            return null;
        }

    }


    /**
     * 获取前最近一批数据，同步到服务器
     * @return
     */
    public JSONArray queryRecentHistoryList(int size){
        String sql = "SELECT * FROM " + TABLE_NAME + " ORDER BY time DESC LIMIT "+size+" OFFSET 0 ";
        return queryHistoryList(sql);
    }


    /**
     * 获取未同步成功的记录
     * @return
     */
    public JSONArray querySycnFailHistoryList(){
        String sql = "SELECT * FROM " + TABLE_NAME + " WHERE needSync = 1 ";
        return queryHistoryList(sql);
    }


    private JSONArray queryHistoryList(String sql) {
        JSONArray array = new JSONArray();
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor c = db.rawQuery(sql, null);
        while (c.moveToNext()) {
            JSONObject object = new JSONObject();
            int pos = c.getInt(c.getColumnIndex("position"));
            int type = c.getInt(c.getColumnIndex("type"));
            int formatType;
            if (type == Constant.OBJECT_TYPE_CARTOON ||
                    type == Constant.OBJECT_TYPE_NOVEL ||
                    type == Constant.OBJECT_TYPE_CHATNOVEL) { //新数据
                formatType = type;
            }else{   //旧数据
                if (type == 1) { //对话小说
                    formatType = Constant.OBJECT_TYPE_CHATNOVEL;
                }else{
                    if (pos < 0) {//漫画
                        formatType = Constant.OBJECT_TYPE_CARTOON;
                    }else{ //小说
                        formatType = Constant.OBJECT_TYPE_NOVEL;
                    }
                }
            }

            object.put("img_url", c.getString(c.getColumnIndex("imgurl")));
            object.put("novel_id", c.getString(c.getColumnIndex("novelid")));
            object.put("progress", c.getString(c.getColumnIndex("progress")));
            object.put("all_num", c.getString(c.getColumnIndex("allnum")));
            object.put("name", c.getString(c.getColumnIndex("name")));
            object.put("type", formatType);
            object.put("position", Math.abs(pos));
            object.put("time", c.getString(c.getColumnIndex("time")));
            object.put("section_id", c.getString(c.getColumnIndex("sectionid")));
            array.add(object);
        }
        c.close();
        db.close();
        return array;
    }

    // 调试信息输出
    private void print(String msg)
    {
        //		System.out.println("DatabaseUtil=====" + msg);
    }

}
